﻿using System;
using System.IO;

namespace XMLParsers.SAX
{
    public class XMLParserSimpleReader
    {
        public XMLParserSimpleElement ReadXML(Stream stream)
        {
            var xmlelement = new XMLParserSimpleElement();
            var tempXmlElement = new XMLParserSimpleElement();
            Char tempChar;
            while (((tempChar = (char)stream.ReadByte()) != '<') && 
                (stream.Position < stream.Length))
                xmlelement.ElementString += tempChar;
            while (((tempChar = (char)stream.ReadByte()) != '>') && 
                (stream.Position < stream.Length))
                xmlelement.Name += tempChar;
            if (xmlelement.Name.Length == 0) throw new IncorrectXMLFormat();
            if (xmlelement.Name[0] == '/') return xmlelement;
            while (stream.Position < stream.Length)
            {
                tempXmlElement = ReadXML(stream);
                if (('/' + xmlelement.Name).ToString() == tempXmlElement.Name)
                {
                    xmlelement.ElementString = tempXmlElement.ElementString;
                    return xmlelement;
                }
                xmlelement.ElementString = "";
                xmlelement.ChildXMLElements.Add(tempXmlElement);
            }
            throw new IncorrectXMLFormat();
        }
    }
}
